package exchange

import (
	"global/libs/structs"
	"github.com/ngaut/log"
	"global/core"
	"strings"
	"fmt"
	"time"
	"global/model"
	"github.com/garyburd/redigo/redis"
	"global/constants"
)

func delPairs(datas []model.ExchangePair, conn redis.Conn, exchange *model.Exchange) {
	if len(datas) == 0 {
		return
	}

	if err := model.ExchangePairModel.Remove(datas); err != nil {
		log.Errorf("Error: %s", err)
		return
	}

	for _, v := range datas {
		key := fmt.Sprintf(constants.SpiderSymbolPairKey, exchange.Slug)
		conn.Do("HDEL", key, v.Symbol)
	}
}

func addPairs(symbols map[string]*structs.Symbol, conn redis.Conn, exchange *model.Exchange, coins map[string]int) {
	if len(symbols) == 0 {
		return
	}
	pairs := make([]model.ExchangePair, 0)
	for _, v := range symbols {
		from := strings.ToLower(v.From)
		to := strings.ToLower(v.To)

		pairs = append(pairs, model.ExchangePair{
			ExchangeMid: 	exchange.Mid,
			ExchangeSlug: 	exchange.Slug,
			Symbol: 		from + "_" + to,
			SymbolBase: 	from,
			SymbolBaseMid: 	coins[from],
			SymbolQuote: 	to,
			SymbolQuoteMid: coins[to],
			CreateTime: 	time.Now(),
			UpdateTime: 	time.Now(),
		})
	}

	if _, err := model.ExchangePairModel.MultiInsert(pairs); err != nil {
		log.Errorf("Error: %s", err)
		return
	}

	// cache
	err := core.SaveSymbolsToExchange(conn, exchange.Slug, symbols)
	if err != nil {
		log.Errorf("Error: save symbol error: %s", err.Error())
	}
}

// 对比获取需要添加和删除的列表
func compare(newSymbols map[string]*structs.Symbol,
	oldSymbols []model.ExchangePair) (map[string]*structs.Symbol, []model.ExchangePair) {
	o := make(map[string]*structs.Symbol)
	delSymbols := make([]model.ExchangePair, 0)
	for _, v := range oldSymbols {
		o[v.Symbol] = &structs.Symbol{From: v.SymbolBase, To: v.SymbolQuote}
		if _, ok := newSymbols[v.Symbol]; !ok {
			delSymbols = append(delSymbols, v)
		}
	}

	// 需要添加的
	addSymbols := make(map[string]*structs.Symbol)
	for key, v := range newSymbols {
		if _, ok := o[key]; !ok {
			addSymbols[key] = v
		}
	}

	return addSymbols, delSymbols
}